package com.ruoyi.feike.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.feike.domain.AnnualReviewy;
import com.ruoyi.feike.domain.BasicInformation;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.domain.vo.AnnualReviewyVO;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/feike/permanent_limit")
public class PermanentLimitController extends BaseController {
    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询feike带任务列表列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/list")
    public TableDataInfo list(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewy> list = annualReviewyService.selectAnnualReviewyAndTaskNameList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/lists")
    public TableDataInfo listById(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewyVO> list = annualReviewyService.selectAnnualReviewyVOList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        startPage();
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy, basicInformation);
        return getDataTable(list);
    }

    //TODO

    /**
     * 导出feike列表
     */
    @PreAuthorize("@ss.hasPermi('feike:feike:export')")
    @Log(title = "feike", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy, basicInformation);
        ExcelUtil<AnnualReviewyHistoryVO> util = new ExcelUtil<AnnualReviewyHistoryVO>(AnnualReviewyHistoryVO.class);
        return util.exportExcel(list, "feike");
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(annualReviewyService.selectAnnualReviewyById(id));
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/ByInstanceId/{instanceId}")
    public AjaxResult getInfoByInstanceId(@PathVariable("instanceId") String instanceId) {
        try {
            return AjaxResult.success(annualReviewyService.selectAnnualReviewyByInstanceId(instanceId));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("数据异常,请联系管理员");
        }
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult add(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.insertAnnualReviewy(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult edit(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.updateAnnualReviewy(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/closeUpdateAnnualReviewyObj/{instanceId}")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult closeUpdateAnnualReviewyObj(@PathVariable String instanceId) {
        String username = SecurityUtils.getLoginUser().getUsername();
        return toAjax(annualReviewyService.closeUpdateAnnualReviewyObj(instanceId, username));
    }

    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/openUpdateAnnualReviewyObj")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult openUpdateAnnualReviewyObj() {
        String username = SecurityUtils.getLoginUser().getUsername();
        annualReviewyService.openUpdateAnnualReviewyObj(username);
        return toAjax(1);
    }

    /**
     * 删除feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(annualReviewyService.deleteAnnualReviewyByIds(ids));
    }

    //TODO--待完善
    @RequestMapping("/uploads")
    public String uploadFile(MultipartFile[] files, HttpServletRequest request) {
        //String realPath = request.getServletContext().getRealPath("/img");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

        //创建年月日文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String res = simpleDateFormat.format(new Date());
        String year = res.substring(0, 4);   //2022
        String month = res.substring(4, 6);  //07
        String day = res.substring(6);      //08
        String fileUploadPath = path + "static/FileUpload/";
        //String fileUploadPath = path + "static/FileUpload/"+File.separator+year+File.separator+month+File.separator+day+File.separator;
        File fileUploadfolder = new File(fileUploadPath);
        //判断目录是否存在，不存在则创建目录
        if (!fileUploadfolder.exists()) {
            fileUploadfolder.mkdirs();
        }
        for (MultipartFile file : files) {
            //获取上传文件的源文件名称
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(fileUploadfolder, newName));
                //打印上传文件的url
                System.out.println(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/FileUpload/" + newName);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传文件失败";
            }
        }
        return "上传文件成功";
    }

    /**
     * 根据id查询，给邮箱模板返回需要的信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @PostMapping(value = "/mailInfo/{instanceId}")
    public AjaxResult getMailInfo(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.selectMailInfoByInstanceId(instanceId));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startDM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startDM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startDM(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/dmSelect")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult dmSelect(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.dmSelect(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startPLM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startPLM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startPLM(map));
        //@PreAuthorize("@ss.hasPermi('feike:feike:query')")
    }

    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/updateMain")
    public AjaxResult updateMain(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.updateMain(map));
    }

    @GetMapping("/getMain/{taskId}")
    public AjaxResult getMain(@PathVariable("taskId") String taskId) {
        return AjaxResult.success(annualReviewyService.getMain(taskId));
    }

    //条件查询--搜索按钮方法
    @GetMapping(value = "/search")
    public TableDataInfo getPageInfo(SearchVo searchVo) {
        PageDomain pageDomain = TableSupport.buildPageRequest();

        Page<ActTaskDTO> hashMaps = annualReviewyService.selectProcessDefinitionSearchList(searchVo, pageDomain);
        return getDataTable(hashMaps);

    }

    @GetMapping("/indexData")
    public ResultData indexData() {
        CustomPage hashMaps = annualReviewyService.indexData();
        return getResult(hashMaps);
    }

    /**
     * 调用第三方接口进行数据查询刷新
     *
     * @return
     */
    @GetMapping("/refresh")
    public AjaxResult getRefreshList() {
        // TODO 后面甲方提供了接口，在进行调用测试，获取数据进行刷新
        String urlStr = "";   //第三方接口路径
        // 添加请求头信息
        Map<String, String> heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");

        /**
         *  get请求
         ** headerMap是添加的请求头，
         */
        HttpResponse response = HttpRequest.get(urlStr)
                .headerMap(heads, false)
                .timeout(5 * 60 * 1000)  // 五分钟超时时间
                .execute();
        System.out.println(response);
        /**
         * post请求
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        // HttpResponse response = HttpRequest.post(urlStr).headerMap(heads, false).body(String.valueOf(jsonObject)).timeout(5 * 60 * 1000).execute();
        Map<String, Object> map = new HashMap<>();

        // "DealerCode":[["L061701","M01002"],["L061702","M01003"]]
        HttpUtil.get(urlStr, map);
        return AjaxResult.success(response);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String originalFilename = file.getOriginalFilename();       // 文件的中文名
            System.out.println("fileName==" + fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("originalFilename", originalFilename);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 多文件上传请求
     */
    @PostMapping("/common/uploads")
    public AjaxResult uploadFiles(MultipartFile[] files) throws Exception {
        try {
            // AjaxResult ajax = AjaxResult.error("上传失败");
            List dataList = new ArrayList();
            for (MultipartFile file : files) {
                Map<String, String> map = new HashMap<>();
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);   // 文件完整路径
                String url = serverConfig.getUrl() + fileName;              // 浏览器可以访问的url路径
                String originalFilename = file.getOriginalFilename();       // 文件的中文名
                System.out.println("fileName==" + fileName);
                map.put("fileName", fileName);
                map.put("url", url);
                map.put("originalFilename", originalFilename);
                dataList.add(map);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data", dataList);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
